package com.zhanghe.study.string;

import org.junit.Test;

/**
 * @author zh
 * @date 2021/6/18 09:52
 */
public class TestString2 {

    @Test
    public void test() {
        String s1 = "z" + "h";
        String s2 = "zh";

        System.out.println(s1 == s2);//true
        System.out.println(s1.equals(s2));//true
    }

    @Test
    public void test1() {
        String s1 = "zh";
        String s2 = "he";
        String s3 = "zh" + "he";
        String s4 = "zhhe";
        String s5 = s1 + "he";
        String s6 = "zh" + s2;
        String s7 = s1 + s2;

        System.out.println(s3 == s4);//true
        System.out.println(s3 == s5);//false
        System.out.println(s3 == s6);//false
        System.out.println(s3 == s7);//false
        System.out.println(s5 == s6);//false
        System.out.println(s5 == s7);//false
        // intern() 判断常量池中是否存在 s6所对应的的字符串值，如果存在，则返回常量池中该字符串值的地址，如果常量池中
        // 不存在，则在常量池中加载一份，并返回此对象的地址
        String s8 = s6.intern();
        System.out.println(s8 == s3);//true
    }

    @Test
    public void test2() {
        String s1 = "z";
        String s2 = "h";
        String s3 = "zh";
        //编译之后变为 (new StringBuilder()).append(s1).append(s2).toString();
        String s4 = s1 + s2;
    }

    @Test
    public void test3(){
        String s1 = new String("1") + new String("1");
        s1.intern();
        String s2 = "11";


        System.out.println(s1 == s2);
    }

    public static void main(String[] args) {
        // 执行完之后常量池中并没有11
        String s1 = new String("1") + new String("1");
        // 由于常量池中没有11，所以常量池指向了s1的内存地址
        s1.intern();
        // 这里是从常量池中取的
        String s2 = "11";
        // 所以两者一致
        System.out.println(s1 == s2);//true
    }


}
